package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.HealthException;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiNiuUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * Description: No Description
 * User: Eric
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealMobileController {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 查询所有
     */
    @GetMapping("/getSetmeal")
    public Result getSetmeal(){

        //查询redis中是否存在setmealList的Key
        Jedis jedis = jedisPool.getResource();
        String setmealList = jedis.get("setmealList");
        List<Setmeal> list;

        //存在key
        if (null != setmealList){
            jedis.close();
            //值为null
            if (setmealList.equals("null")) {
                throw  new HealthException("请30秒后再次尝试访问");
            } else {
                //值非null
                TypeReference<List<Setmeal>> ref = new TypeReference<List<Setmeal>>() {
                };
                list = JSON.parseObject(setmealList, ref);

            }
        } else {

            //不存在key,查询数据库
            list = setmealService.findAll();

            //数据库中有值,存入redis并返回
            if (null != list){

                //遍历list，将所有套餐存入setmealRanking
                list.forEach(setmeal -> {

                    Double setmealExist = jedis.zscore("setmealRanking", JSON.toJSONString(setmeal));
                    if (null == setmealExist){
                        jedis.zadd("setmealRanking",0,JSON.toJSONString(setmeal));
                    }
                });

                Set<String> setmealRanking = jedis.zrevrange("setmealRanking", 0, -1);
                List<Setmeal> listRanking = new ArrayList<>();
                setmealRanking.forEach(s -> {
                    listRanking.add(JSON.parseObject(s,Setmeal.class));
                });
                jedis.set("setmealList",JSON.toJSONString(listRanking));
                TypeReference<List<Setmeal>> ref = new TypeReference<List<Setmeal>>() {
                };
                list = JSON.parseObject(jedis.get("setmealList"), ref);
                jedis.close();

            } else {
                //数据库中查询不到
                jedis.setex("setmealList",30,"null");//防止缓存穿透
                jedis.close();
                throw  new HealthException("请30秒后再次尝试访问");
            }
        }

        // 套餐里有图片有全路径吗? 拼接全路径
        list.forEach(s->{
            s.setImg(QiNiuUtils.DOMAIN + s.getImg());
        });
        return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS,list);
    }

    /**
     * 查询套餐详情
     */
    @GetMapping("/findById")
    public Result findById(int id){
        // 调用服务查询详情
        Setmeal setmeal = setmealService.findById(id);
        // 设置图片的完整路径
        setmeal.setImg(QiNiuUtils.DOMAIN + setmeal.getImg());
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
    }

    /**
     * 查询套餐详情
     */
    @GetMapping("/findDetailById")
    public Result findDetailById(int id){

        //查询redis中是否存在setmealList的Key
        Jedis jedis = jedisPool.getResource();
        String setmealId = "setmealDetail_"+id;
        String setmealDetail = jedis.get(setmealId);
        Setmeal setmeal;

        //存在key
        if (null != setmealDetail){
            jedis.close();
            //值为null
            if (setmealDetail.equals("null")) {
                throw  new HealthException("请30秒后再次尝试访问");
            } else {
                //值非null
                setmeal = JSON.parseObject(setmealDetail,Setmeal.class);
                Setmeal setmealT = new Setmeal();
                BeanUtils.copyProperties(setmeal,setmealT);
                setmealT.setCheckGroups(null);
                jedis.zincrby("setmealRanking",1,JSON.toJSONString(setmealT));
            }
        } else {

            //不存在key,查询数据库
            setmeal= setmealService.findDetailById(id);

            //数据库中有值,存入redis并返回
            if (null != setmeal){
                jedis.setex(setmealId, new Random().nextInt(7200) + 3600*24,JSON.toJSONString(setmeal));
                Setmeal setmealT = new Setmeal();
                BeanUtils.copyProperties(setmeal,setmealT);
                setmealT.setCheckGroups(null);
                jedis.zincrby("setmealRanking",1,JSON.toJSONString(setmealT));
                jedis.close();

            } else {
                //数据库中查询不到
                jedis.setex(setmealId,30,"null");//防止缓存穿透
                jedis.close();
                throw  new HealthException("请30秒后再次尝试访问");
            }
        }

        // 设置图片的完整路径
        setmeal.setImg(QiNiuUtils.DOMAIN + setmeal.getImg());
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
    }

    /**
     * 查询套餐详情
     */
    @GetMapping("/findDetailById2")
    public Result findDetailById2(int id){
        // 调用服务查询详情
        Setmeal setmeal = setmealService.findDetailById2(id);
        // 设置图片的完整路径
        setmeal.setImg(QiNiuUtils.DOMAIN + setmeal.getImg());
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
    }

    /**
     * 查询套餐详情
     */
    @GetMapping("/findDetailById3")
    public Result findDetailById3(int id){
        // 调用服务查询详情
        Setmeal setmeal = setmealService.findDetailById3(id);
        // 设置图片的完整路径
        setmeal.setImg(QiNiuUtils.DOMAIN + setmeal.getImg());
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
    }
}
